﻿using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Newtonsoft.Json.Serialization;
using UFIDA.U9.WSS.ProxyService.Json;
using UFIDA.U9.WSS.ProxyService.Utils;
using UFSoft.UBF.Util.Log;

namespace UFIDA.U9.WSS.ProxyService.Behavior.WebHttp.Base
{
    public abstract class NewtonsoftJsonDispatchFormatter : IDispatchMessageFormatter
    {
        protected static readonly ILogger Logger = LoggerManager.GetLogger("NewtonsoftJsonDispatchFormatter");
        protected readonly OperationDescription _operation;

        protected NewtonsoftJsonDispatchFormatter(OperationDescription operation)
        {
            _operation = operation;
        }

        public void DeserializeRequest(Message message, object[] parameters)
        {
            byte[] rawBody = MessageHelper.ReadRawBody(ref message, false);
            if (rawBody == null) return;
            //解析参数
            ParseParameters(rawBody, parameters);
        }

        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            IContractResolver resolver = GetSerializeReplyContractResolver();
            byte[] body = JsonHelper.GetReturnJsonBody(result, resolver);
            Message replyMessage = Message.CreateMessage(messageVersion, _operation.Messages[1].Action,
                new RawBodyWriter(body));
            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name,
                new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpResponseMessageProperty respProp = new HttpResponseMessageProperty();
            respProp.Headers[HttpResponseHeader.ContentType] = "application/json;charset=utf-8";
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);
            return replyMessage;
        }

        /// <summary>
        ///     解析参数
        /// </summary>
        /// <param name="rawBody"></param>
        /// <param name="parameters"></param>
        protected abstract void ParseParameters(byte[] rawBody, object[] parameters);

        /// <summary>
        ///     获取回复的ContractResolver
        /// </summary>
        /// <returns></returns>
        protected abstract IContractResolver GetSerializeReplyContractResolver();
    }
}